package com.zhuizikejithreeig.cn.threeigkeji.loginfo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.zhuizikejithreeig.cn.been.CarBeen;
import com.zhuizikejithreeig.cn.been.CarInfoBeen;
import com.zhuizikejithreeig.cn.been.RegisterBeen;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.MainActivity;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

public class CarInformationActivity extends BasicActivity implements View.OnClickListener {
    private TextView mName1;
    private EditText mName4;
    private LinearLayout mName5;
    private TextView mName8;
    private EditText mName9;
    private TextView mName7;
    private LinearLayout mName11;
    private ImageView mAgree;
    private TextView mAgreeText;
    private boolean b = true;
    private boolean isFirst = false;
    private static final List<String> options1Items = new ArrayList<>();
    private TimePickerView pvTime;
    private String mPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_car_information);
        pvTime = getTimePickerView();
        mName1 = (TextView) findViewById(R.id.name1);
        mName8 = (TextView) findViewById(R.id.name8);
        mName7 = (TextView) findViewById(R.id.name7);
        mAgreeText = (TextView) findViewById(R.id.agree_text);
        mName4 = (EditText) findViewById(R.id.name4);
        mName5 = (LinearLayout) findViewById(R.id.name5);
        mName9 = (EditText) findViewById(R.id.name9);
        mName11 = (LinearLayout) findViewById(R.id.name11);
        mAgree = (ImageView) findViewById(R.id.agree);

        mName1.setOnClickListener(this);
        mAgreeText.setOnClickListener(this);
        mAgree.setOnClickListener(this);
        mName11.setOnClickListener(this);
        mName5.setOnClickListener(this);

        //设置同意协议书
        if (b) {
            mAgree.setSelected(true);
            b = !b;
        }

        //获取车辆型号
        options1Items.clear();
        if (isConnected()) {
            getListName();
        }


    }


    @Override
    public void onClick(View v) {
        InputMethodManager imm = null;
        switch (v.getId()) {

            //提交
            case R.id.name1:
                if (isConnected()) {
                    mPhone = Utils.getString(ContectUtils.PHONESAVE);
                    if (TextUtils.isEmpty(mPhone) && !Utils.isPhoneNO(mPhone)) {
                        skipOtherActivity(LoginActivity.class, true);
                        CompontApplayCation.loginNeedFinsh = false;
                        return;
                    }
                    postFrom();
                } else {
                    ToastMake.showToast(getResources().getString(R.string.string57));
                }
                break;
            //选择时间
            case R.id.name11:
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//////隐藏软键盘 //
////                imm.hideSoftInputFromWindow(mName11.getWindowToken(), 0);
//////显示软键盘
////                imm.showSoftInputFromInputMethod(mName11.getWindowToken(), 0);
//                //切换软键盘的显示与隐藏
//                imm.toggleSoftInputFromWindow(mName11.getWindowToken(), 0, InputMethodManager.HIDE_NOT_ALWAYS);

                imm = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mName11.getWindowToken(), 0);


                pvTime.show();

                break;
            //同意圆圈
            case R.id.agree:
                if (b) {
                    mAgree.setSelected(true);
                } else {
                    mAgree.setSelected(false);
                }
                b = !b;
                break;
            //协议书
            case R.id.agree_text:
                skipOtherActivity(Agreement.class, false);
                break;
            //车辆类型
            case R.id.name5:

                imm = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mName5.getWindowToken(), 0);

                //如果初始化的已经获取车辆名称的列表
                if (options1Items.size() != 0) {
                    chioceCar();
                } else {
                    //如果初始化的没有获取车辆名称的列表
                    if (isConnected()) {
                        isFirst = true;
                        getListName();
                    } else {
                        ToastMake.showToast(getResources().getString(R.string.string57));
                    }
                }
                break;
        }
    }


    private void chioceCar() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(CarInformationActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String s = options1Items.get(options1);
                mName8.setText(s);
                CompontApplayCation.driverInfo.setCarPostion(options1 + 1 + "");
                mName8.setTextColor(getResources().getColor(R.color.textColor5));
            }
        })
                //                        .setSubmitText("确定")//确定按钮文字
                //                        .setCancelText("取消")//取消按钮文字
                .setTitleText("车辆类型")//标题
                .setSubCalSize(20)//确定和取消文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                //                        .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
                //                        .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
                //                        .setContentTextSize(18)//滚轮文字大小
                //                        .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                //                        .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                //                        .setLinkage(false)//设置是否联动，默认true
                //                        .setLabels("省", "市", "区")//设置选择的三级单位
                //                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //                        .setCyclic(false, false, false)//循环与否
                //                        .setSelectOptions(1, 1, 1)  //设置默认选中项
                //                        .setOutSideCancelable(false)//点击外部dismiss default true
                //                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvOptions.setPicker(options1Items);
        pvOptions.show();
    }


    @NonNull
    private TimePickerView getTimePickerView() {
        TimePickerView pvTime = new TimePickerView.Builder(CarInformationActivity.this, new TimePickerView.OnTimeSelectListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                long chioceDate = Utils.dateToLong(date2);
                long curDate = Utils.getCurDate();
                if (chioceDate >= curDate) {
                    ToastMake.showToast("时间必须小于当前时间");
                    return;
                } else {
                    String time = getTime(date2);
                    mName7.setText(time);
                    mName7.setTextColor(getResources().getColor(R.color.textColor5));
                }
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                //                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                //                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                //                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                //                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                //                        .setRangDate(startDate,endDate)//起始终止年月日设定
                //                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        return pvTime;
    }


    //提交车辆信息
    private void postFrom() {
        String carNumberA = mName4.getText().toString().trim();
        String carType = mName8.getText().toString().trim();
        String carMasterName = mName9.getText().toString().trim();
        String carDate = mName7.getText().toString().trim();
        if (TextUtils.isEmpty(carNumberA)) {
            ToastMake.showToast(getResources().getString(R.string.string92));
            return;
        }

        String carNumberB = Utils.GetDeleteShort(carNumberA);
        String carNumber = carNumberB.toUpperCase();

        System.out.println("carNumber" + carNumber);
        if (carNumber.length() != 7) {
            ToastMake.showToast(getResources().getString(R.string.string13));
            return;
        }
        if (!Utils.isCar(carNumber)) {
            ToastMake.showToast(getResources().getString(R.string.string14));
            return;
        }

        if (TextUtils.isEmpty(carType)) {
            ToastMake.showToast(getResources().getString(R.string.string15));
            return;
        }
        if (TextUtils.isEmpty(carMasterName)) {
            ToastMake.showToast(getResources().getString(R.string.string9));
            return;
        }

        if (TextUtils.equals(carDate, getResources().getString(R.string.string11))) {
            ToastMake.showToast(getResources().getString(R.string.string16));
            return;
        }

        final Map<String, String> map = new HashMap<>();
        map.put("phone", mPhone);
        map.put("nickname", CompontApplayCation.driverInfo.getName());
        map.put("name", carMasterName);
        map.put("car_regist_time", replace(carDate));
        map.put("begin_drive_time", replace(CompontApplayCation.driverInfo.getReceive()));
        map.put("car_number", carNumber);
        map.put("car_type", CompontApplayCation.driverInfo.getCarPostion());

        showProgrees("提交中,请稍等.....");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String separator = File.separator;
                OkHttpUtils.post()//
                        .addFile("portrait_img", separator + "01.png", CompontApplayCation.driverInfo.getIcon())//
                        .addFile("identity_card", separator + "02.png", CompontApplayCation.driverInfo.getId())//
                        .url(UriContect.PERFECT)
                        .params(map)
                        .build()//
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastMake.showToast(getResources().getString(R.string.string58));
                                hideProgree();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                hideProgree();
                                CarInfoBeen been = GsonUtil.parseJsonToBean(response, CarInfoBeen.class);
                                if (been == null) {
                                    ToastMake.showToast(getResources().getString(R.string.string58));
                                    return;
                                }
                                if (!TextUtils.equals(been.getError_code(), "0")) {
                                    ToastMake.showToast(been.getMsg());
                                    return;
                                } else {
                                    //上传完成以后,跳转到绑定界面
                                    if (been.getData().getStatus() != null) {
                                        Utils.setString(been.getData().getStatus(), ContectUtils.STATUS);
                                    } else {
                                        Utils.setString("3", ContectUtils.STATUS);
                                    }
                                    //保存名字
                                    if (CompontApplayCation.driverInfo.getName() != null && !TextUtils.isEmpty(CompontApplayCation.driverInfo.getName())) {
                                        Utils.setString(CompontApplayCation.driverInfo.getName(), ContectUtils.NICKNAME);
                                    }
                                    //保存图片
                                    if (been.getData().getPortrait_img() != null && !TextUtils.isEmpty(been.getData().getPortrait_img())) {
                                        Utils.setString(been.getData().getPortrait_img(), ContectUtils.IMAGEICONURI);
                                    }
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            skipOtherActivity(BundingSetActivity.class, true);
                                            finish();
                                        }
                                    });
                                }
                            }
                        });
            }
        }).start();

    }

    /**
     * 时间转换
     *
     * @return
     */
    public String getTime(Date date) {//可根据需要自行截取数据显示
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy/MM/dd");
        return format.format(date);
    }

    public void getListName() {
        showProgrees("加载中请稍等....");
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .post()
                        .url(UriContect.CARS)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (isFirst) {
                                    ToastMake.showToast(getResources().getString(R.string.string58));
                                }
                                hideProgree();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                hideProgree();
                                CarBeen mesBeen = GsonUtil.parseJsonToBean(response, CarBeen.class);
                                if (mesBeen == null) {
                                    ToastMake.showToast(getResources().getString(R.string.string58));
                                    return;
                                }
                                if (!TextUtils.equals(mesBeen.getError_code(), "0")) {
                                    ToastMake.showToast(mesBeen.getMsg());
                                    return;
                                } else {

                                    for (CarBeen.DataBean dataBean : mesBeen.getData()) {
                                        options1Items.add(dataBean.getCarTypeName());
                                    }
                                    //如果是点击的话,就出现选择界面,否则不出现,并且必须在主线程中
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (isFirst) {
                                                chioceCar();
                                                isFirst = false;
                                            }

                                        }
                                    });
                                }
                            }
                        });
            }
        }).start();
    }

    //对字符串进行切割向后台传递
    public String replace(String a) {
        String c = a.substring(0, 4);
        String b = a.substring(5, 7);
        String d = a.substring(8, a.length());
        return c + b + d;
    }

}

